package index

import (
	"html/template"
	"log"
	"net/http"

	essayTemplate "gitee.com/taadis/nook/template/essay"
)

func init() {
	log.Println("init / index")
	http.HandleFunc("/", index)
}

func index(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		getIndex(w, r)
	default:
		http.Error(w, "", http.StatusMethodNotAllowed)
	}
}

func getIndex(w http.ResponseWriter, r *http.Request) {
	data, err := essayTemplate.ListData()
	if err != nil {
		log.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	filenames := []string{
		"template/root.tmpl",
		"template/index.tmpl",
	}
	tmpl, err := template.ParseFiles(filenames...)
	if err != nil {
		log.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	tmpl = template.Must(tmpl, err)
	err = tmpl.ExecuteTemplate(w, "root", data)
	if err != nil {
		log.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
